package com.jh.concurrent.juc.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author JH_Wong
 * @projectName newforward
 * @title SemaphoreDemo.java
 * @package com.jh.concurrent.juc.semaphore
 * @description Semaphore信号量测试Demo
 * @date 2019-05-21 08:50
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 10; i++) {
            new Thread(new Car(semaphore, i)).start();
        }
    }

    static class Car extends Thread {
        private Semaphore semaphore;
        private int num;

        public Car(Semaphore semaphore, int num) {
            this.semaphore = semaphore;
            this.num = num;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println("第" + num + "辆车停进来了");
                TimeUnit.SECONDS.sleep(2);
                System.out.println("第" + num + "辆车走了");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
